import 'package:flutter/material.dart';
import 'dart:async';

class NFTAuctionScreen extends StatefulWidget {
  final Map<String, dynamic> nftData;

  const NFTAuctionScreen({Key? key, required this.nftData}) : super(key: key);

  @override
  State<NFTAuctionScreen> createState() => _NFTAuctionScreenState();
}

class _NFTAuctionScreenState extends State<NFTAuctionScreen>
    with TickerProviderStateMixin {
  late Timer _timer;
  Duration _timeLeft = const Duration(hours: 23, minutes: 45, seconds: 30);
  final TextEditingController _bidController = TextEditingController();
  
  // 拍卖数据
  double _currentBid = 1250.0;
  double _minBidIncrement = 50.0;
  int _totalBids = 24;
  String _highestBidder = 'User***123';
  
  // 动画控制器
  late AnimationController _pulseController;
  late Animation<double> _pulseAnimation;
  
  // 出价历史
  List<Map<String, dynamic>> _bidHistory = [
    {'bidder': 'User***123', 'amount': 1250.0, 'time': '2分钟前'},
    {'bidder': 'User***456', 'amount': 1200.0, 'time': '5分钟前'},
    {'bidder': 'User***789', 'amount': 1150.0, 'time': '8分钟前'},
    {'bidder': 'User***321', 'amount': 1100.0, 'time': '12分钟前'},
    {'bidder': 'User***654', 'amount': 1050.0, 'time': '15分钟前'},
  ];

  @override
  void initState() {
    super.initState();
    _startTimer();
    _initAnimations();
  }

  void _initAnimations() {
    _pulseController = AnimationController(
      duration: const Duration(seconds: 1),
      vsync: this,
    );
    _pulseAnimation = Tween<double>(
      begin: 1.0,
      end: 1.1,
    ).animate(CurvedAnimation(
      parent: _pulseController,
      curve: Curves.easeInOut,
    ));
    _pulseController.repeat(reverse: true);
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_timeLeft.inSeconds > 0) {
        setState(() {
          _timeLeft = Duration(seconds: _timeLeft.inSeconds - 1);
        });
      } else {
        timer.cancel();
      }
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    _pulseController.dispose();
    _bidController.dispose();
    super.dispose();
  }

  void _placeBid() {
    final bidAmount = double.tryParse(_bidController.text);
    if (bidAmount == null || bidAmount <= _currentBid) {
      _showErrorDialog('出价必须高于当前最高价');
      return;
    }
    
    if (bidAmount < _currentBid + _minBidIncrement) {
      _showErrorDialog('出价增幅不能少于 ${_minBidIncrement.toInt()} USDT');
      return;
    }

    setState(() {
      _bidHistory.insert(0, {
        'bidder': '您',
        'amount': bidAmount,
        'time': '刚刚',
      });
      _currentBid = bidAmount;
      _totalBids++;
      _highestBidder = '您';
    });
    
    _bidController.clear();
    _showSuccessDialog('出价成功！');
  }

  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('出价失败'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showSuccessDialog(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('成功'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      appBar: AppBar(
        title: const Text(
          'NFT拍卖',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Color(0xFF333333),
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Color(0xFF333333)),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.share, color: Color(0xFF333333)),
            onPressed: () {
              // 分享功能
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            _buildNFTInfo(),
            _buildAuctionInfo(),
            _buildBidSection(),
            _buildBidHistory(),
          ],
        ),
      ),
    );
  }

  Widget _buildNFTInfo() {
    return Container(
      margin: const EdgeInsets.all(20),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // NFT图片
          Center(
            child: Container(
              width: 200,
              height: 200,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: widget.nftData['categoryBgColor'],
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(16),
                child: Image.network(
                  widget.nftData['imageUrl'],
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      color: widget.nftData['categoryBgColor'],
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              widget.nftData['categoryText'],
                              style: TextStyle(
                                fontSize: 32,
                                fontWeight: FontWeight.bold,
                                color: widget.nftData['categoryTextColor'],
                              ),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              widget.nftData['artworkName'],
                              style: TextStyle(
                                fontSize: 16,
                                color: widget.nftData['categoryTextColor'],
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
          const SizedBox(height: 20),
          
          // NFT信息
          Text(
            widget.nftData['name'],
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '作者: ${widget.nftData['author']}',
            style: const TextStyle(
              fontSize: 16,
              color: Color(0xFF666666),
            ),
          ),
          const SizedBox(height: 8),
          if (widget.nftData['ranking'] != null)
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              decoration: BoxDecoration(
                color: const Color(0xFF1890FF).withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                '排名: #${widget.nftData['ranking']}',
                style: const TextStyle(
                  fontSize: 14,
                  color: Color(0xFF1890FF),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildAuctionInfo() {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 0, 20, 20),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '拍卖信息',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 16),
          
          // 倒计时
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [Color(0xFFFF6B35), Color(0xFFFF8E53)],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.access_time,
                  color: Colors.white,
                  size: 24,
                ),
                const SizedBox(width: 12),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '拍卖结束倒计时',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    AnimatedBuilder(
                      animation: _pulseAnimation,
                      builder: (context, child) {
                        return Transform.scale(
                          scale: _pulseAnimation.value,
                          child: Text(
                            _formatDuration(_timeLeft),
                            style: const TextStyle(
                              fontSize: 20,
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontFamily: 'monospace',
                            ),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 16),
          
          // 当前最高价
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '当前最高价',
                    style: TextStyle(
                      fontSize: 14,
                      color: Color(0xFF666666),
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '${_currentBid.toStringAsFixed(0)} USDT',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF1890FF),
                    ),
                  ),
                ],
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  const Text(
                    '出价次数',
                    style: TextStyle(
                      fontSize: 14,
                      color: Color(0xFF666666),
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '$_totalBids 次',
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF333333),
                    ),
                  ),
                ],
              ),
            ],
          ),
          
          const SizedBox(height: 12),
          
          // 最高出价者
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: const Color(0xFFF0F8FF),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.emoji_events,
                  color: Color(0xFF1890FF),
                  size: 20,
                ),
                const SizedBox(width: 8),
                Text(
                  '当前最高出价者: $_highestBidder',
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xFF1890FF),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBidSection() {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 0, 20, 20),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '参与竞拍',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 16),
          
          // 出价输入
          TextField(
            controller: _bidController,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              labelText: '出价金额 (USDT)',
              hintText: '最低出价: ${(_currentBid + _minBidIncrement).toStringAsFixed(0)}',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: const BorderSide(color: Color(0xFFE0E0E0)),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: const BorderSide(color: Color(0xFF1890FF), width: 2),
              ),
              prefixIcon: const Icon(Icons.attach_money, color: Color(0xFF1890FF)),
            ),
          ),
          
          const SizedBox(height: 16),
          
          // 快速出价按钮
          Row(
            children: [
              Expanded(
                child: _buildQuickBidButton((_currentBid + 50).toStringAsFixed(0)),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _buildQuickBidButton((_currentBid + 100).toStringAsFixed(0)),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: _buildQuickBidButton((_currentBid + 200).toStringAsFixed(0)),
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          // 出价按钮
          SizedBox(
            width: double.infinity,
            height: 48,
            child: ElevatedButton(
              onPressed: _placeBid,
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFF6B35),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                elevation: 0,
              ),
              child: const Text(
                '立即出价',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQuickBidButton(String amount) {
    return GestureDetector(
      onTap: () {
        _bidController.text = amount;
      },
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 8),
        decoration: BoxDecoration(
          border: Border.all(color: const Color(0xFF1890FF)),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Center(
          child: Text(
            '+$amount',
            style: const TextStyle(
              fontSize: 14,
              color: Color(0xFF1890FF),
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBidHistory() {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 0, 20, 20),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            spreadRadius: 0,
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '出价记录',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Color(0xFF333333),
            ),
          ),
          const SizedBox(height: 16),
          
          ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: _bidHistory.length,
            separatorBuilder: (context, index) => const Divider(
              color: Color(0xFFF0F0F0),
              height: 1,
            ),
            itemBuilder: (context, index) {
              final bid = _bidHistory[index];
              final isCurrentUser = bid['bidder'] == '您';
              
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 12),
                child: Row(
                  children: [
                    Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: index == 0 
                            ? const Color(0xFF52C41A) 
                            : const Color(0xFFE0E0E0),
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                bid['bidder'],
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: isCurrentUser 
                                      ? FontWeight.bold 
                                      : FontWeight.normal,
                                  color: isCurrentUser 
                                      ? const Color(0xFF1890FF) 
                                      : const Color(0xFF333333),
                                ),
                              ),
                              Text(
                                '${bid['amount'].toStringAsFixed(0)} USDT',
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                  color: index == 0 
                                      ? const Color(0xFF52C41A) 
                                      : const Color(0xFF333333),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 4),
                          Text(
                            bid['time'],
                            style: const TextStyle(
                              fontSize: 12,
                              color: Color(0xFF999999),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    String hours = twoDigits(duration.inHours);
    String minutes = twoDigits(duration.inMinutes.remainder(60));
    String seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$hours:$minutes:$seconds';
  }
}